import { getArticleList, getNewArticleList } from '@/store/actions/article'
import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import ArticleItem from '../ArticleItem/ArticleItem'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import styles from './index.module.scss'
type Props = {
    channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  console.log('ArticleList')
  const dispatch = useDispatch()
  useEffect(() => {
    // dispatch(getArticleList(channelId, Date.now()))
  }, [])
  const { timestamp, articles } = useSelector((state:RootState) => {
    const t = state.article[channelId]
    return t || { articles: [] }
  })

  const loadMore = async () => {
    console.log('加载更多')
    // 发请求...
    await dispatch(getArticleList(channelId, timestamp || Date.now()))
  }

  const onRefresh = async () => {
    console.log('......')
    // 加载最新的数据: 传入最新的时间戳
    await dispatch(getNewArticleList(channelId))
  }
  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        {/* 文章列表中的每一项 */}
        {
          articles.map(it => (<div className="article-item" key={it.art_id}>
            <ArticleItem item={it}/>
          </div>))
        }
        {/* 假设最多显示50条 */}
        <InfiniteScroll hasMore={articles.length < 50} loadMore={loadMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
